package com.oocl.o2o.merchant.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.merchant.dao.FoodDao;
import com.oocl.o2o.merchant.entity.Food;

@Repository
public class FoodDaoImpl implements FoodDao {
	@PersistenceContext
	private EntityManager em;

	@Override
	public Food add(Food t) {
		try {
			em.persist(t);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Food update(Food t) {
		try {
			t = em.merge(t);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Food delete(String id) {
		try {
			Food food = em.find(Food.class, id);
			food.setMerchant(null);
			return food;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Food findById(String id) {
		try {
			return em.find(Food.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<Food> findAll() {
		try {
			String jpql = "select f from Food f";
			TypedQuery<Food> query = em.createQuery(jpql, Food.class);
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
